package edg.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Database {
	
	private static final Connection DB_CONNECTION = connect();
	
	/*
	private static final String DB_SERVER = "localhost";
	private static final String DB_NAME = "edg";
	private static final String DB_USER = "root";
	private static final String DB_PASSWORD = "";
	//*/
	
	//*
	private static final String DB_SERVER = "db.thejfx.net";
	private static final String DB_NAME = "cs320_edg_db";
	private static final String DB_USER = "edg_admin";
	private static final String DB_PASSWORD = "cs320edg1234";
	//*/
	
	/**
	 * This method is not meant for other modules to call directly.
	 * @param sql The SQL query to be executed.
	 * @return A Statement object with which you can retrieve results.
	 */
	static Statement query(String sql) {
		//System.out.println(sql); // query debugging
		Statement statement = null;
		try {
			statement = DB_CONNECTION.createStatement();
			statement.execute(sql);
		}
		catch(Exception ex) {
			System.out.println("Got an exception:");
			System.out.println(ex);
			ex.printStackTrace();
			//ex.printStackTrace(); // query debugging
			//return null;
		}
		return statement;
	}
	
	/**
	 * Should not be called by other classes (and can't be).  Used to connect to
	 * the database upon first instantiation of the Database class.
	 * @return Connection object for database.
	 */
	private static Connection connect() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection("jdbc:mysql://" + DB_SERVER + "/"
					+ DB_NAME, DB_USER, DB_PASSWORD);
		}
		catch(Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	/**
	 * This method is not meant for other modules to call directly.
	 * @param input Potentially malicious user input.
	 * @return Sanitized input with single quotes escaped.
	 */
	static String sanitize(String input) {
		// TODO: lookup java built-in stuff...not a priority though
		int i = input.indexOf("'");
		while(i != -1) {
			input = input.substring(0, i) + "\\'" + input.substring(i+1);
			i = input.indexOf("'", i+2);
		}
		return input;
	}
	
}